const request = require("../../../../../utils/request");

// pages/index/confirm-order/confirm-order.js
Page({

    /**
     * 页面的初始数据
     */
    data: {

        // 优惠券弹窗
        isShowCoupon: false,

        //优惠券选项卡
        currentTab: 0,

        selectCoupon: null,
        // 选择配送方式弹窗
        isShowType: false,
        use_point: '1',
        //选择配送方式选项卡, 1快递，2门店自提
        receipt_type: 1,
        ids: '', //下单商品id
        type: '', //拼团2 普通 1
        location: {}, //配送点
        addressInfo: null, //收货地址信息
        uship_id: '', //收货地址id
        memo: '', //备注
        payment_code: "wechatpay", //支付方式

        cart_list: [], //购买的商品
        cartInfo: {}, //商品总金额信息
        showPay: false,

        order_id: '', //下单后的订单id
        coupon_code: '', //优惠券编码
        coupon_price: "",
        couponType: 1, //1可用 2不可用
        couponList: [], //优惠券列表
        couponList_usable: [],
        couponList_unusable: [],
        userInfo: {},

        isShowNum: 2, //展示更多

        isZiying: false, //自营-- 快递，无需传store_id

        ushopInfo: {},
        isShowCartList: false,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if (options.store_id == 0) {
            this.setData({
                isZiying: true
            })
        }
        this.setData({
            ids: options.id,
            type: options.type
        })

    },
    onShow() {

        this.initData()
        this.getcoupon()
    },
    initData() {
        let location = wx.getStorageSync('localXiaoqu')
        this.setData({
            location
        })
        let uship_id = wx.getStorageSync('addressId')
        this.setData({
            uship_id
        })
        this.getMorenAddress()
        this.getGoods()
        this.getUserInfo()
    },
    getUserInfo() {
        let _this = this
        request._get('/api?method=user.info', {}, 'noload').then(res => {
            console.log(res, '个人信息')
            _this.setData({
                userInfo: res.data
            })
        })
    },
    /**
     * 优惠券弹窗
     */
    showCouponWindow() {
        // getApp().toast('功能开发中...')
        this.setData({
            isShowCoupon: true
        })
    },
    hideCouponWindow() {
        this.setData({
            isShowCoupon: false
        })
    },
    // 获取优惠券
    getcoupon() {
        let _this = this
        request._post('/api?method=order.createOrderCoupons', {
            cart_ids: this.data.ids,
        }).then(res => {
            if (res.data.usable.length > 0) {
                res.data.usable.forEach(function (obj, index) {
                    obj.checked = false
                })
            }
            this.setData({
                couponList: res.data.usable,
                couponList_usable: res.data.usable,
                couponList_unusable: res.data.unusable
            })

        })
    },
    // 查看地图
    toPoint() {
        wx.navigateTo({
            url: '/pages/home/pages/my/peisongdian/peisongdian',
        })
    },
    // 选择收货地址
    toSelectAddress() {
        wx.navigateTo({
            url: '/pages/mine/pages/my/my-address/my-address?type=1',
        })
    },
    getMorenAddress() {
        let _this = this
        let uship_id = this.data.uship_id
        request._post('/api?method=user.getusership', {}).then(res => {
            if (uship_id) {
                _this.setData({
                    addressInfo: res.data.find(el => el.id == uship_id)
                })
            } else {
                _this.setData({
                    addressInfo: res.data.find(el => el.is_def == 1),
                    uship_id: res.data.find(el => el.is_def == 1).id
                })
            }
            _this.getPeiSong()


        })
    },

    // 获取商品信息
    getGoods() {
        let xiaoqu = wx.getStorageSync('localXiaoqu') ? wx.getStorageSync('localXiaoqu').id : ''
        let _this = this
        request._post('/api?method=cart.cartlist', {
            cart_ids: this.data.ids,
            selected_ids: this.data.ids,
            type: this.data.type,
            coupon_code: this.data.selectCoupon ? this.data.selectCoupon.coupon_code : '',
            xiaoqu
        }).then(res => {
            console.log(res, 334)
            _this.setData({
                cart_list: res.data.goods_list,
                cartInfo: res.data,
             
                'cartInfo.youhuiquan': Number(res.data.youfeiquan),
                "cartInfo.pay_total": Number(res.data.pay_total)
            })
            if(_this.data.use_point == 1){
              var tempprice = parseFloat(_this.data.cartInfo.pay_total) - parseFloat(_this.data.cartInfo.point_dikou)
              tempprice = tempprice.toFixed(2)
              _this.setData({
                payCount: tempprice
              })
            }

        })
    },




    /**
     * 选项卡
     */
    swithNav(e) {
        const c = e.currentTarget.dataset;
        this.setData({
            currentTab: c.current,
            couponType: c.current == 1 ? 2 : 1,
            couponList: [],
        })
        if (c.current == 0) {
            this.setData({
                couponList: this.data.couponList_usable,
            })
        } else {
            this.setData({
                couponList: this.data.couponList_unusable,
            })
        }
        // this.getcoupon()

    },
    // 勾选优惠券
    selectCoupon(e) {
        let {
            index,
            item
        } = e.currentTarget.dataset
        let couponList = this.data.couponList
        let selectCoupon = this.data.selectCoupon
        item.checked = !item.checked
        if (item.checked) {
            selectCoupon = item
        } else {
            selectCoupon = {}
        }
        couponList[index] = Object.assign(couponList[index], item)
        couponList.forEach(function (obj, i) {
            if (i != index) {
                obj.checked = false
            }
        })
        console.log(selectCoupon, 'Dfdfkdf')
        this.setData({
            couponList,
            selectCoupon
        })
    },
    // 确定选择
    sureCoupon() {
        let _this = this
        let item = this.data.couponList.find(el => el.checked)
        if (!item) {
            return getApp().toast('请选择一张优惠券')
        }
        this.setData({
            coupon_code: item.coupon_code,
           
        })
        this.userCoupon(item)

    },
    // 使用优惠券
    // 
    userCoupon(item) {
        let _this = this
        request._post('/api?method=coupon.getcoupon', {
            promotion_id: item.id
        }).then(res => {
           this.setData({
            isShowCoupon: false,
           })
            setTimeout(function () {
                _this.getGoods()
            }, 1000)
        })
    },
    // 支付方式
    radioChange(e) {
        console.log(e)
        let val = e.detail.value
        this.setData({
            payment_code: val
        })
    },
    // 积分抵扣

    radioPointChange(e) {
      console.log(e)
      let val = e.detail.value
      this.setData({
        use_point: val
      })
  },
    /**
     * 选择配送方式弹窗
     */
    showTypeWindow() {
        if (this.data.isZiying) {
            return
        }
        this.setData({
            isShowType: true
        })
    },
    hideTypeWindow() {
        this.setData({
            isShowType: false
        })
    },

    /**
     * 选项卡
     */
    tabClick(e) {
        const d = e.currentTarget.dataset;
        this.setData({
            receipt_type: d.id
        })
        this.initData()
        this.hideTypeWindow()
    },

    /**
     *切换配送点 
     */
    map() {
        wx.navigateTo({
            url: '../../index/peisongdian/peisongdian',
        })
    },
    // 输入框操作
    inputWrite(e) {
        this.setData({
            [e.currentTarget.dataset.name]: e.detail.value
        })
    },
    // 立即支付
    pay() {
        let _this = this



        _this.setOrder()
    },
    // 创建订单
    setOrder() {
        let _this = this
        let addressInfo = this.data.addressInfo
        let payment_code = this.data.payment_code
        let pay_password = wx.getStorageSync('userInfo').pay_password
        if (!addressInfo) {
            return wx.showToast({
                title: '请选择收货地址',
                icon: 'none'
            })
        }
        // 未设置支付密码
        if (payment_code == 'balancepay' && !pay_password) {
            wx.navigateTo({
                url: '/pages/mine/pages/my/setting-password/setting-password',
            })
            return
        }
        // 设置了支付密码,余额不足
        if (payment_code == 'balancepay') {
            //余额支付
            if (parseFloat(this.data.userInfo.balance) == 0) {
                getApp().toast('余额不足~')
                return
            }
        }
        // 零元支付


        let obj = {
            uship_id: this.data.uship_id,
            receipt_type: this.data.receipt_type,
            lading_name: addressInfo ? addressInfo.name : '',
            lading_mobile: addressInfo ? addressInfo.mobile : '',
            memo: this.data.memo,
            cart_ids: this.data.ids,
            coupon_code: this.data.selectCoupon ? this.data.selectCoupon.coupon_code : '',
            order_type: this.data.type,
            use_point: this.data.use_point,
        }
        if (this.data.receipt_type == 2) {
            obj.xiaoqu = wx.getStorageSync('localXiaoqu') ? wx.getStorageSync('localXiaoqu').id : ''
        }
        request._post('/api?method=order.create', obj).then(res => {
            let order_id = res.data[0]
            _this.setData({
                order_id
            })
            _this.payOrder()
        })
    },
    // 支付
    payOrder() {
        let payment_code = this.data.payment_code
        // 设置了支付密码
        if (payment_code == 'balancepay') {
            this.setData({
                showPay: true
            })
        } else {
            // 微信支付
            this.payApi()
        }
    },
    // 验证密码成功,调支付接口
    pwdcheck_success() {
        this.setData({
            showPay: false
        })
        this.payApi()
    },
    // 余额直接不支付，关闭支付弹框
    pwdcheck_fail() {
        let _this = this
        this.setData({
            showPay: false
        })
        getApp().toast('支付失败')
        setTimeout(function () {
            if (_this.data.type == 1) {
                wx.redirectTo({
                    url: '/pages/mine/pages/my/order-details/order-details?isconfim=1&id=' + _this.data.order_id,
                });
            } else {
                wx.redirectTo({
                    url: '/pages/home/pages/my/group-details/group-details?id=' + _this.data.order_id,
                });
            }

        }, 1000)
    },
    // 支付接口api
    payApi() {
        // 支付接口
        let payment_code = this.data.payment_code
        let order_id = this.data.order_id
        let _this = this
        request._post('/api?method=user.pay', {
            ids: order_id,
            payment_code: payment_code,
            payment_type: 1
        }, 'noload').then(res => {
            if (payment_code == 'balancepay') {
                //余额支付
                getApp().toast(res.msg)
                getApp().sendMessage(_this.data.order_id)
                setTimeout(function () {
                    if (_this.data.type == 1) {
                        wx.reLaunch({
                            url: '/pages/mine/pages/my/order-details/order-details?isconfim=1&id=' + _this.data.order_id,
                        });
                    } else {
                        wx.redirectTo({
                            url: '/pages/home/pages/my/group-details/group-details?id=' + _this.data.order_id,
                        });
                    }

                }, 1000)
            } else {
                this.wxPay(res.data)
            }
        }).catch(function (res) {
            // 报错支付失败
            if(res.data.data == '10059'){
              wx.reLaunch({
                url: '/pages/mine/pages/my/order-details/order-details?isconfim=1&id=' + _this.data.order_id,
              })
            }
        })

    },
    wxPay(obj) {
        let _this = this
        wx.requestPayment({
            timeStamp: obj.timeStamp,
            nonceStr: obj.nonceStr,
            package: obj.package,
            signType: obj.signType,
            paySign: obj.paySign,
            signType: obj.signType,
            success(res) {
                console.log(res)
                if (_this.data.type == 1) {
                    wx.redirectTo({
                        url: '/pages/mine/pages/my/order-details/order-details?isconfim=1&id=' + _this.data.order_id,
                    })
                } else {
                    wx.redirectTo({
                        url: '/pages/home/pages/my/group-details/group-details?id=' + _this.data.order_id,
                    });
                }
                getApp().sendMessage(_this.data.order_id)
            },
            fail(res) {
                // 跳转待支付详情页
                if (_this.data.type == 1) {
                    wx.redirectTo({
                        url: '/pages/mine/pages/my/order-details/order-details?isconfim=1&id=' + _this.data.order_id,
                    })
                } else {
                    wx.redirectTo({
                        url: '/pages/home/pages/my/group-details/group-details?id=' + _this.data.order_id,
                    });
                }

            }
        })
    },

    toShowMore(e) {
        console.log(e, 2323)
        let index = e.currentTarget.dataset.index
        this.setData({
            isShowNum: this.data.isShowCartList ? 2 : this.data.cart_list[index].goods.length,
            isShowCartList: !this.data.isShowCartList
        })
    },
    // 根据收货地址获取配送点 /api?method=order.createBefore
    getPeiSong() {
        request._post('/api?method=order.createBefore', {
            uship_id: this.data.uship_id
        }).then(res => {
            console.log(res, 3434)
            this.setData({
                ushopInfo: res.data
            })
        })
    }




})